from collections import OrderedDict

from .models import GoodsChannel


def get_categories():
    """
    获取商品分类数据
    :return: 分类数据字典
    """
    # 定义有序字典用来存储商品分类数据
    categories = OrderedDict()
    # 根据组号及组内顺序查询频道信息
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # 遍历频道
    for channel in channels:
        group_id = channel.group_id
        # 判断组号是否在categories中
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 当前频道的分类

        # 追加当前频道的一级分类信息到上述字典中
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []
            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    return categories
